<template>
  <el-dialog
    v-model="state.dialogVisible"
    :before-close="handleClose"
    :destroy-on-close="true"
    width="80%"
    :append-to-body="true"
    custom-class="my-dialog"
    top="5vh"
  >
    <template #header>
      <div class="my-header">
        <div class="title-hr"></div>
        <div>
          <span class="title-top">试算详情</span>
          {{ state.title }}
        </div>
      </div>
    </template>
    <div class="dialog-container">
      <div class="check-box">
        <span>依据方案:</span>
        <el-checkbox
          :label="state.baseScheme[0].scName"
          v-model="state.checkedScheme"
          @change="handleCheckedJointScheme"
        ></el-checkbox>
        <span>试算方案:</span>
        <el-checkbox-group
          v-model="state.trialIds"
          v-for="(item, index) in state.trialData"
          :key="index"
          @change="handleChangeTryScheme"
        >
          <el-checkbox :label="item.trialName" />
        </el-checkbox-group>
      </div>
      <div class="tabs-box">
        <el-tabs
          v-model="activeName"
          stretch
          type="border-card"
          class="demo-tabs"
          @tab-change="handleChangeTabs"
        >
          <el-tab-pane label="单站成果详情" name="first" lazy>
            <div class="result-detail-box">
              <div class="left-detail">
                <div class="tabs-title">
                  <el-input v-model="state.name" placeholder="请输入" clearable>
                    <template #append>
                      <el-icon @click="handleClickIcon(state.name)"><Search /></el-icon>
                    </template>
                  </el-input>
                </div>
                <el-collapse
                  v-model="state.collapseActive"
                  accordion
                  @change="handleSwitchCollapse"
                >
                  <el-collapse-item name="1">
                    <template #title>
                      <span class="mg10">水库/坝/闸</span>
                    </template>
                    <div class="tabs-list">
                      <div
                        :class="['list-item', currentIndex == index ? 'active' : '']"
                        v-for="(item, index) in state.sectionArr.filter(
                          (v) => v.sttp == 'RR' || v.sttp == 'DM' || v.stop == 'DD'
                        )"
                        :key="index"
                      >
                        <el-tooltip
                          :content="item.blknm"
                          placement="top"
                          :disabled="item.blknm.length < 6"
                        >
                          <span @click="handleClickTabs(item, index)">{{ item.blknm }}</span>
                        </el-tooltip>
                      </div>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item name="2">
                    <template #title>
                      <span class="mg10">水文站</span>
                    </template>
                    <div class="tabs-list">
                      <div
                        :class="['list-item', currentIndex == index ? 'active' : '']"
                        v-for="(item, index) in state.sectionArr.filter((v) => v.sttp == 'ZQ')"
                        :key="index"
                      >
                        <el-tooltip
                          :content="item.blknm"
                          placement="top"
                          :disabled="item.blknm.length < 6"
                        >
                          <span @click="handleClickTabs(item, index)">{{ item.blknm }}</span>
                        </el-tooltip>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <div class="right-detail">
                <div class="top-ul-box">
                  <div class="ul-box">
                    <div
                      v-for="(item, index) in state.showBgItem"
                      :key="index"
                      :class="['ul-item', state.flagItem == index ? 'clickBg' : '']"
                      @click="handleClickShow(index)"
                    >
                      {{ item }}
                    </div>
                  </div>
                </div>
                <div class="echarts-table-box">
                  <div class="echarts-box" v-show="state.tableShow">
                    <SwDispatchChart
                      chart-key="jonitResult"
                      height="100%"
                      :x-labels="state.sysTimes"
                      :servers="state.servers"
                      v-if="state.waterFlag == 1"
                    />
                    <SkDispatchChart
                      chart-key="jonitResult"
                      height="100%"
                      :x-labels="state.sysTimes"
                      :servers="state.servers"
                      v-if="state.waterFlag == 2"
                    />
                  </div>
                  <div
                    :class="['table-box', state.tableShow ? '' : 'table-box-show']"
                    v-show="!state.showTable"
                  >
                    <el-table :data="state.servers[0]?.ccResult" border>
                      <el-table-column prop="tm" label="时间" show-overflow-tooltip align="center">
                      </el-table-column>
                      <el-table-column
                        prop="fp"
                        label="降雨量"
                        show-overflow-tooltip
                        align="center"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="jp"
                        label="净雨值"
                        show-overflow-tooltip
                        align="center"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="name"
                        label="入库流量（实测/预报）"
                        show-overflow-tooltip
                        align="center"
                      >
                        <template #default="{ row }">
                          {{ `${row.rq !== '' ? row.rq : '--'}/${row.fq !== '' ? row.fq : '--'}` }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="address"
                        label="出库流量（实测/预报）"
                        show-overflow-tooltip
                        align="center"
                      >
                        <template #default="{ row }">
                          {{
                            `${row.rotq !== '' ? row.rotq : '--'}/${
                              row.otq !== '' ? row.otq : '--'
                            }`
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="address"
                        label="水库水位（实测/预报）"
                        show-overflow-tooltip
                        align="center"
                      >
                        <template #default="{ row }">
                          {{
                            `${row.rzr !== '' ? row.rzr : '--'}/${row.zr !== '' ? row.zr : '--'}`
                          }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
                <div class="feature-box">
                  <div class="title">特征统计</div>
                  <el-table :data="state.servers" style="width: 100%" height="100px">
                    <el-table-column prop="fcV" label="洪峰流量" align="center" />
                    <el-table-column prop="fcMxt" label="峰现时间" align="center" />
                    <el-table-column prop="fcMxotq" label="最大出流" align="center" />
                    <el-table-column prop="flCoef" label="产流系数" align="center" />
                  </el-table>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="调度对比" name="second" lazy>
            <div class="table-box">
              <el-table :data="state.tableData" style="width: 100%">
                <el-table-column prop="name" label="试算方案名称" align="center" width="200">
                  <template #default="scope">
                    {{ scope.row.name }}
                  </template>
                </el-table-column>

                <el-table-column
                  :label="item.blknm"
                  prop=""
                  align="center"
                  v-for="(item, index) in state.tableData[0].list"
                  :key="index"
                >
                  <el-table-column prop="date" label="最高水位前/后" align="center">
                    <template #default="{ row }">
                      <!-- {{ row }} -->
                      {{ row.list[index].fcMxzF }} / {{ row.list[index].fcMxzB }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="date"
                    label="最大出库流量前/后"
                    align="center"
                    v-if="item.sttp == 'RR'"
                  >
                    <template #default="{ row }">
                      {{ row.list[index].fcMxotqF }}/{{ row.list[index].fcMxotqB }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="date"
                    label="洪峰流量前/后"
                    align="center"
                    v-if="item.sttp == 'ZQ'"
                  >
                    <template #default="{ row }">
                      {{ row.list[index].fcMxqF }}/{{ row.list[index].fcMxqB }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="date"
                    label="削峰率"
                    align="center"
                    v-if="item.sttp == 'RR'"
                  >
                    <template #default="{ row }">
                      {{ row.list[index].xfl }}
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
//水文
import SwDispatchChart from '@/components/app-echart/sw-dispatch-chart.vue'
//水库
import SkDispatchChart from '@/components/app-echart/sk-dispatch-chart.vue'
import {
  getJointTrialSection,
  getJointTrialResult,
  getJointTrialResultCompara,
  getManualSchemesresult
} from '@/services/modules/dispatch-manage'
import emitter from '@/utils/bus'
const state = reactive({
  checkedScheme: false,
  baseScheme: [],
  tableData: [],
  zoneId: '',
  rangeCode: '',
  name: '',
  dialogVisible: false,
  tryRes: [],
  trialData: [],
  //试算id 集合
  jointTrialIds: [],
  trialIds: [],
  sourceServers: [],
  waterFlag: 2,
  flagItem: 0,
  showBgItem: ['图', '混', '表'],
  showTable: true,
  tableShow: true,
  servers: [],
  collapseActive: '1',
  sectionArr: [],
  //时间
  sysTimes: []
})
const currentIndex = ref(0)
const activeName = ref('first')
// const ruleFormRef = ref(null);
// onMounted(() => {
//   getJointTrialSectionList()
// })
function handleSwitchCollapse(val) {
  currentIndex.value = 0
  if (val == 1) {
    handleClickTabs(
      state.sectionArr.filter((v) => v.sttp == 'RR' || v.sttp == 'DM' || v.stop == 'DD')[0],
      0
    )
  } else {
    handleClickTabs(state.sectionArr.filter((v) => v.sttp == 'ZQ')[0], 0)
  }
}
/**
 * tabs
 */
const handleChangeTabs = () => {
  nextTick(() => {
    emitter.emit('initEcharts')
  })
}
/**
 * 水库水文站获取
 * @params
 */
const getJointTrialSectionList = () => {
  getJointTrialSection({ zoneId: state.zoneId, rangeCode: state.rangeCode, blknm: '' }).then(
    (res) => {
      if (res.code === 200) {
        state.sectionArr = res.data
        state.blkcdId = state.sectionArr.filter(
          (v) => v.sttp == 'RR' || v.sttp == 'DM' || v.stop == 'DD'
        )[0].blkcd
        getJointTrialResultList(
          state.sectionArr.filter((v) => v.sttp == 'RR' || v.sttp == 'DM' || v.stop == 'DD')[0]
            .blkcd
        )
      }
    }
  )
}
// 点击水库或水文站
async function handleClickTabs(item, index) {
  if (item) {
    state.blkcdName = item?.blknm
    state.blkcdId = item?.blkcd ? item?.blkcd : ''
    currentIndex.value = index
    // 当选中的为水库时
    if (item.sttp == 'RR') {
      // 点击为水库
      state.waterFlag = 2
    } else {
      // 点击的为水文站
      state.waterFlag = 1
    }
    // 点击水库，将存储的方案结果和id，图表传的值 都清空，并默认选中第一个方案
    state.servers = []
    await getJointTrialResultList(state.blkcdId)

    if (state.checkedScheme) {
      handleCheckedJointScheme(true)
    }
  }
}
/**
 * 计算结果
 */
const getJointTrialResultList = (blkcd) => {
  return new Promise((resolve, reject) => {
    if (state.jointTrialIds.length) {
      getJointTrialResult({ trialIds: state.jointTrialIds.join(','), blkcd: blkcd }).then((res) => {
        if (res.code === 200) {
          if (res.data.length)
            state.servers = res.data.map((e) => {
              return {
                ccResult: e.result,
                scName: e.trialName,
                ...e
              }
            })
          resolve(state.servers)
        }
      })
    } else {
      state.servers = []
      resolve(state.servers)
    }
  })
}
/**
 * 调度结果对比
 */
const getJointTrialResultComparaList = () => {
  getJointTrialResultCompara({ trialIds: state.jointTrialIds.join(',') }).then((res) => {
    if (res.code === 200) {
      filterDiff(res.data)
    }
  })
}
/**
 * 数据处理
 */
const filterDiff = (data) => {
  const groupedById = data.reduce((acc, obj) => {
    const key = obj.trialId
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})

  let result = Object.values(groupedById)
  result = result.map((item, index) => {
    return {
      name: item[0].trialName,
      list: item,
      id: index + 1
    }
  })
  state.tableData = result
  console.log('result', result)
}
/**
 * 获取试算id集合
 * @params arr:state.trialData checkeds:state.trialIds
 */
const getTrialIds = (arr, checkeds) => {
  let ids = []
  arr.forEach((item) => {
    checkeds.forEach((e) => {
      if (item.trialName == e) {
        ids.push(item.id)
      }
    })
  })
  return ids
}
function handleOpenDetails(item) {
  state.checkedScheme = false
  state.baseScheme = item.baseScheme
  state.zoneId = item.zoneId
  state.rangeCode = item.rangeCode
  state.trialIds = []
  console.log(item, '列表')
  // 特征统计
  // state.tryRes = item.result
  state.dialogVisible = true
  // 试算方案
  state.trialData = item.trialList
  state.trialData.forEach((e) => {
    state.trialIds.push(e.trialName)
  })
  state.jointTrialIds = getTrialIds(state.trialData, state.trialIds)
  console.log('666', state.jointTrialIds)
  getJointTrialSectionList()
  getJointTrialResultComparaList()
  let res = item.result
  console.log(item.result, '结构')
  // state.servers = item.result
  nextTick(() => {
    emitter.emit('initEcharts')
  })
}
defineExpose({ handleOpenDetails })

// 关闭弹框的回调
function handleClose() {
  state.dialogVisible = false
}
/**
 * 修改依据方案
 */
const handleCheckedJointScheme = (item) => {
  if (item) {
    getManualSchemesresult({ scid: state.baseScheme[0].scid, blkcd: state.blkcdId }).then((res) => {
      if (res.code === 200) {
        if (res.data.length) {
          let arr = res.data.map((e) => {
            return {
              ccResult: e.result,
              scName: e.scName,
              ...e
            }
          })
          state.servers = [...state.servers, ...arr]
          console.log(state.servers, '77')
        }
      }
    })
  } else {
    state.servers = state.servers.filter((item) => !item.scid)
  }
}
//
function handleChangeTryScheme(arr) {
  state.checkedScheme = false
  state.trialIds = []
  state.trialData.forEach((e) => {
    state.trialIds.push(e.trialName)
  })
  state.trialIds = state.trialIds.filter((item) => {
    return arr.includes(item)
  })
  state.jointTrialIds = getTrialIds(state.trialData, state.trialIds)
  getJointTrialResultList(state.blkcdId)
  getJointTrialResultComparaList()
  const filteredServers = state.sourceServers.filter((child) => arr.includes(child.trialName))
  console.log('666', state.trialIds, state.jointTrialIds)
  // let array = []
  // state.servers = state.sourceServers
  // state.servers.forEach((child) => {

  //   arr.forEach((e) => {
  //     if (child.scName == e) {
  //       array.push(child)
  //     }
  //   })
  // })
  console.log(filteredServers, '点击3')
  state.servers = filteredServers
  nextTick(() => {
    emitter.emit('initEcharts')
  })
}

//展开
function handleClickShow(val) {
  state.flagItem = val
  if (val == 0) {
    // 图
    state.showTable = true
    state.tableShow = true

    nextTick(() => {
      emitter.emit('initEcharts')
    })
  } else if (val == 1) {
    // 混
    state.showTable = false
    state.tableShow = true
  } else {
    //表
    state.showTable = false
    // 将图关闭
    state.tableShow = false
  }
  nextTick(() => {
    // emitter.emit('clearEcharts')
    emitter.emit('initEcharts')
  })
}
</script>
<style lang="less">
.el-dialog.my-dialog {
  .el-dialog__body {
    padding: 5px 20px !important;
  }
}
</style>
<style lang="less" scoped>
.dialog-container {
  overflow-y: auto;
  height: 83vh;
  .check-box {
    height: 50px;
    align-items: center;
    display: flex;
    span {
      margin-right: 20px;
      margin-left: 20px;
    }
    .el-checkbox-group {
      margin-right: 10px;
    }
  }
  .tabs-box {
    height: calc(100% - 100px);
    :deep(.el-tabs) {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 30px);
        box-sizing: border-box;
        .el-tab-pane {
          height: 100%;
          .result-detail-box {
            display: flex;
            height: 100%;
            .left-detail {
              width: 200px;
              height: 100%;
              border: 1px solid #c8c2c29d;
              margin-right: 10px;
              box-sizing: border-box;
              border-radius: 3px;
              .tabs-title {
                // margin-top: 15px;
                // margin-left: 10px;
                height: 30px;
                background: #f2f2f2;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                span {
                  font-weight: 600;
                }
              }
              .el-collapse-item__wrap {
                height: calc(100% - 30px);
                // overflow-y: auto;
              }
              .el-collapse {
                height: calc(100% - 50px);
                .mg10 {
                  margin-left: 10px;
                  width: 100%;
                  text-align: center;
                }
                .el-collapse-item.is-active {
                  height: calc(100% - 82px);
                  .el-collapse-item__wrap {
                    height: 100%;
                    .el-collapse-item__content {
                      height: calc(100% - 80px);
                      overflow-y: auto;
                    }
                  }
                }
              }
              .tabs-list {
                // height: calc(100% - 30px);
                // background: #d7d4d427;
                // overflow-y: auto;
                .list-item {
                  display: flex;
                  align-items: center;
                  width: 100%;
                  height: 30px;
                  text-align: center;
                  cursor: pointer;
                  &.active {
                    span {
                      color: #0154db;
                    }
                  }
                  span {
                    width: 100%;
                    color: black;
                    display: inline-block;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  }
                  .position-btn {
                    margin-right: 20px;
                  }
                  .position-btn:hover {
                    color: #0154db;
                  }
                }
                .list-item:hover {
                  width: 100%;
                  height: 30px;
                  cursor: pointer;
                  span {
                    color: #0154db;
                  }
                }
              }
            }
            .right-detail {
              width: calc(100% - 300px);
              flex: 1;
              height: 100%;
              overflow-y: auto;
              .top-ul-box {
                display: flex;
                justify-content: flex-end;
                height: 50px;
                // width: 100%;
                .ul-box {
                  display: flex;
                  justify-content: flex-end;
                  align-items: center;
                  height: 30px;
                  // width: 100%;
                  border-radius: 20px;

                  background-color: rgba(1, 84, 219, 0.3);
                  .ul-item {
                    width: 30px;
                    height: 100%;

                    line-height: 30px;
                    text-align: center;
                    border-radius: 20px;
                    // background-color: #0154db;
                    color: #ffffff;
                    cursor: pointer;
                    &:hover {
                      background-color: #0154db;
                      color: wheat;
                    }
                  }
                  .clickBg {
                    background-color: #0154db;
                  }
                }
              }
              .echarts-table-box {
                display: flex;
                width: 100%;
                height: 600px;
                // height: calc(100% - 120px);

                position: relative;

                .echarts-box {
                  flex: 1;
                  min-width: 49%;
                  height: 100%;
                  // height: calc(100%);
                  // padding: 5px;
                  position: relative;
                  .show-btn {
                    cursor: pointer;
                    position: absolute;
                    right: 0px;
                    top: 0px;
                  }
                }
                .table-box {
                  width: 50%;
                  margin-left: 1%;
                  position: relative;
                  .el-table {
                    height: 100%;
                  }
                  .hide-btn {
                    cursor: pointer;
                    position: absolute;
                    height: 20px;
                    top: 10px;
                    right: 0;
                    z-index: 10;
                  }
                }
                .table-box-show {
                  width: 100% !important;
                }
              }
              .feature-box {
                margin-top: 20px;
                .title {
                  color: #409eff;
                  margin: 5px 0 5px 20px;
                }
              }
            }
          }
        }
      }
    }
  }
}

.el-dialog {
  .my-header {
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    height: 35px;
    border-bottom: 2px solid #eee;
    font-size: 21px;
    .title-hr {
      height: 18px;
      border: #4fc0f1 2px solid;
      margin-right: 10px;
    }
    .title-top {
      color: #4fc0f1;
    }
  }
}
</style>
